<template>
	<el-dialog :visible.sync="options.showDialog" width="700px" class="evalDialog">
		<h3 class="import-title">导入</h3>
		<div class="switch-outer">
			<div class="outer-block" @click="openAddTemplate">
				<i class="el-icon-plus"></i>
				<p>新增模版</p>
			</div>
			<div class="outer-block" @click="switchTemplateMsg.showDialog = true;">
				<i class="el-icon-check"></i>
				<p>选择模版</p>
			</div>
		</div>
		
		
		<p class="template-name" v-if="templateSelected">{{templateName}}</p>
		<div class="select-month" v-if="templateSelected">
			<select v-model="month" placeholder="请选择" class="select-input">
			    <option :class="{'selected-color': item.selected}" v-for="(item,index) in selectList" :key="index" :label="item.value" :value="item.value">
			    </option>
			</select>
		</div>
		<p class="tips">*根据所选模版内容要求录入对应数据表格文件</p>
		 <el-checkbox class="checkbox" v-model="checked" @change="checkchange">暂不展示</el-checkbox>
		<div class="sub-btn" v-if="templateSelected">
			<el-button v-if="!month" @click="importExcel" type="primary" size="small" style="width: 100px;">确定</el-button>
			
			<el-upload v-else class="upload-demo" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadOk">
				<el-button size="small" type="primary" style="width: 100px;">确定</el-button>
			</el-upload>
		</div>
		<!-- 新增模板弹窗 -->
		<payrollAddTemplate :options="addTemplateMsg" @updateTemplateList="updateTemplateList"></payrollAddTemplate>
		<!-- 选择模板弹窗 -->
		<payrollSwitchTemplate ref="switchTemplate" :options="switchTemplateMsg" @useTemplate="useTemplate"
			@editTemplate="editTemplate" >
		</payrollSwitchTemplate>
		<!-- 导入结果 -->
		<payrollImportResult :options="importResult" @submitResult="submitResult"></payrollImportResult>
	</el-dialog>
</template>

<script>
export default{
	components: {
		payrollAddTemplate: () => import("@/component/pages/payrollAddTemplate.vue"),
		payrollSwitchTemplate: () => import("@/component/pages/payrollSwitchTemplate.vue"),
		payrollImportResult: () => import("@/component/pages/payrollImportResult.vue"),
	},
	props:{
		options:{
			type: Object,
			require: true
		}
	},
	data(){
		return {
			checked:false,
			judge:0,
			templateName: '这是模板名称',							//模板名称
			month: '',												//当前选中月份
			selectList: [											//月份选择列表
				/* {
					value: '2021-03',
					selected: false
				} */
			],	
			templateSelected: false,									//模板展示
			
			/* 新增模板数据 */
			addTemplateMsg: {
				showDialog: false,										//
				title: '新增模板制作',									//标题
				userInfo: {},											//用户信息
				
			},
			/* 选择模板数据 */
			switchTemplateMsg:{
				showDialog: false,			
				
			},
			/* 被选中的模板数据 */
			usedInfo:{},
			/* 导入结果数据 */
			importResult: {
				showDialog: false,							
				list: [],
				data: [],
			},
			/* 校验结果 */
			verificatResult: {}
		}
	},
	methods:{
		checkchange(row){
			console.log(row)
			if(row){
				this.judge=0;
				}else{this.judge=1};
		},
		/* 导入表格excel */
		importExcel(){
			if(!this.templateName || !this.month){
				this.$message.warning('请选择模板和发放月份！');
				return false;
			}
		},
		//文件上传前校验
		beforeAvatarUpload(file){
			console.log(file);
			let Xls = file.name.split('.');
			if(Xls[1] === 'xls'||Xls[1] === 'xlsx'){
				return file
			}else {
				this.$message.error('上传文件只能是 xls/xlsx 格式!');
				return false
			}
		},
		/* 接收excel中的数据 */
		uploadOk(val){
			let reader = new FileReader();
			FileReader.prototype.readAsBinaryString = f => {
				let binary = "";
				let data = '';
				let outdata = '';
				reader.onload = (e)=> {
					let bytes = new Uint8Array(reader.result);
					let length = bytes.byteLength;
					for (let i = 0; i < length; i++) {
						binary += String.fromCharCode(bytes[i]);
					}
					let XLSX = require("xlsx");
					data = XLSX.read(binary, {type: "binary"});
					outdata = XLSX.utils.sheet_to_json(data.Sheets[data.SheetNames[0]]);
					this.conversion(outdata);
				}
				reader.readAsArrayBuffer(val.file);
			}
			reader.readAsBinaryString(val.file);
		},
		//数据格式转换
		conversion(arr){
			console.log(arr);
			let list = [];
			let expectedLength = this.usedInfo.payrollNameDetailsList.length;
			let isEmpty = false;
			if(arr && arr.length > 0){
				arr.forEach(item => {
					let nav = {
						"payrollDetailsItem": [],
						"staffName": '',
						"staffIdCard": "",
						"takeHomePay": ""
					};
					let actualLength = 0;
					for(let key in item){
						actualLength += 1;
						if(key == '姓名'){
							nav.staffName = item[key];
						}else if(key == '身份证号码'){
							nav.staffIdCard = item[key];
						}else if(key == '账户收入'){
							nav.takeHomePay = item[key];
						}else{
							nav.payrollDetailsItem.push(item[key]);
						}
					}
					nav.distributedDate = this.month;
					nav.enteringName = localStorage.getItem('checkHuman');
					
					if(expectedLength != actualLength){
						isEmpty = true;
						return false;
					}
					
					list.push(nav);
				})
			}
			console.log(list);
			
			if(isEmpty){
				this.$message.warning('表格中含有空格，导入失败，请将信息填写完整后重新导入！');
				return false;
			}
			
			let params = {
				templateid: this.usedInfo.templateid,
				payrollToLeadDetailRequests: list
			}
			this.$payrollAxios.post('/v1/PayRoll/judgeTolead',params).then(res => {
				console.log(res);
				if(res.data.code === 1){
					console.log(this.usedInfo);
					let result = res.data.data;
					this.verificatResult = result;
					this.importResult.list = [];
					this.importResult.data = [];
					this.usedInfo.payrollNameDetailsList.forEach((item,index) => {
						if(item == '姓名'){
							this.importResult.list.push({title: '姓名', prop: 'staffName', isClick: false});
						}else if(item == '身份证号码'){
							this.importResult.list.push({title: '身份证号码', prop: 'staffIdCard', isClick: false});
						}else if(item == '账户收入'){
							this.importResult.list.push({title: '账户收入', prop: 'takeHomePay', isClick: false});
						}else{
							this.importResult.list.push({title: item, prop: 'prop'+(index-3), isClick: false});
						}
					})
					this.importResult.list.push({title: '结果', prop: 'outcome', isClick: false});
					
					result.payrollToLeadDetailRequests.forEach((item,index) => {
						let nav = {
							staffName: item.staffName,
							staffIdCard: item.staffIdCard,
							takeHomePay: item.takeHomePay,
							outcome: item.result == '0'?'失败':'成功'
						};
						item.payrollDetailsItem.forEach((sub,key) => {
							nav['prop'+key] = sub;
						})
						item.judge=this.judge;
						this.importResult.data.push(nav);
					})
					
					this.importResult.showDialog = true;
				}else{
					this.$message.warning(res.data.message);
				}
			})
		},
		/* 提交导入结果数据 */
		submitResult(){
			this.$payrollAxios.post('/v1/PayRoll/insertPayrolldetails',this.verificatResult).then(res => {
				console.log(res);
				if(res.data.code === 1){
					this.$message.success('提交成功！');
					this.importResult.showDialog = false;
					this.options.showDialog = false;
					this.month = '';
					this.templateName = '';
					this.templateSelected = false;
					this.$emit('updateList');
				}else{
					this.$message.warning(res.data.message);
				}
			})
		},
		
		/* 打开新增模板 */
		openAddTemplate(){
			this.addTemplateMsg.title = '新增模板制作';
			this.addTemplateMsg.showDialog = true;
		
		},
		/* 使用模板 */
		useTemplate(data){
			console.log(data);
			this.usedInfo = data;
			this.switchTemplateMsg.showDialog = false;
			this.templateSelected = true;
			this.templateName = data.templateName;
			this.getUsedMonth(data);
		},
		/* 查看使用过的月份 */
		getUsedMonth(data){
			this.handleMonthStyle();
			this.$payrollAxios.post('/v1/PayRoll/selectDistributedDate',{templateid: data.templateid}).then(res => {
				console.log(res);
				if(res.data.code === 1){
					let result = res.data.data;
					this.selectList.forEach((item,index) => {
						result.forEach(sub => {
							if(item.value == sub){
								item.selected = true;
							}
						})
					})
				}else{
					this.$message.warning(res.data.message);
				}
			})
		},
		/* 查看/编辑模板 */
		editTemplate(data){
			console.log(data);
			this.addTemplateMsg.title = '查看/编辑模板';
			this.addTemplateMsg.userInfo = data;
			this.addTemplateMsg.showDialog = true;
			
		},
		/* 编辑模板之后更新模板列表 */
		updateTemplateList(){
			this.$refs.switchTemplate.getTemplateList();
		},
		/* 初始化月份样式 */
		handleMonthStyle(){
			this.selectList = [];
			let date = new Date();
			let years = date.getFullYear();
			let months = date.getMonth() + 2;
			for(let i = 0; i < 24; i++){
				if(months == 1){
					months = 12;
					years -= 1;
				}else{
					months -= 1;
				}
				
				if(months < 10){
					this.selectList.push({
						value: years + '-0' + months,
						selected: false,
					})
				}else{
					this.selectList.push({
						value: years + '-' + months,
						selected: false,
					})
				}
				
			}
		}
	},
	watch:{
		'options.showDialog'(){
			if(this.options.showDialog){
				this.handleMonthStyle();
			}
		}
	}
}
</script>

<style scoped="scoped">
.import-title{padding: 30px 0;font-size: 24px;text-align: center;}
.switch-outer{display: flex;margin: 20px 40px;justify-content: space-around;}
.outer-block{border: 1px solid #000;width: 240px;height: 170px;border-radius: 20px;text-align: center;}
.outer-block i{font-size: 50px;margin-top: 30px;}
.outer-block p{font-size: 24px;margin-top: 20px;cursor: pointer;}
.template-name{width: 320px;margin: 20px 0 20px 75px;border: 1px solid #000;height: 40px;border-radius: 4px;line-height: 40px;padding-left: 20px;}
.select-month{margin: 20px 0 20px 75px;}
.select-input{width: 320px;height: 40px;padding-left: 16px;}
.select-input option{line-height: 24px;padding: 5px 0;}
.selected-color{color: blue;}
.tips{color: red;font-size: 16px;margin-left: 75px;padding-bottom: 20px;}
.sub-btn{text-align: center;padding: 20px 0 30px;}
.checkbox{position: absolute;
    top: 292px;
    right: 20px;}
</style>
